const { ipcMain, BrowserWindow, dialog, clipboard } = require('electron');
const { QH_Events } = require('../common/events');
const { sendMsg } = require('../utils/eleMainUtils');
const FileUtils = require('../utils/fileUtils');
const { getIPAddress } = require('../utils/ipUtils');

ipcMain.handle(QH_Events.DEBUG_INFO, (evidence, msg) => {
  console.log('=========msg=========:', msg);
});

ipcMain.handle(QH_Events.SHOW_DIALOG, (evidence, title, msg) => {
  dialog.showErrorBox(title, msg);
});

ipcMain.handle(QH_Events.TEST_LT, (evidence) => {
  let menu = new Menu();
  let menuItem = new MenuItem({
    label: '插入',
    submenu: [
      {
        label: '图片',
        click: () => {
          sendMsg(QH_Events.INSERT_ELEMENT, 'img', BrowserWindow.getAllWindows()[0]);
        },
      },
      {
        label: '文字',
        click: () => {
          sendMsg(QH_Events.INSERT_ELEMENT, 'label');
        },
      },
      {
        label: '容器',
        click: () => {
          sendMsg(QH_Events.INSERT_ELEMENT, 'div');
        },
      },
    ],
  });
  menu.append(menuItem);
  menu.popup();
});

ipcMain.handle(QH_Events.GET_LOCAL_IP, (evidence) => {
  return getIPAddress();
});

ipcMain.handle(QH_Events.GET_PAGE_INFO, async (evidence) => {
  let str = await FileUtils.readFile();
  if (str) {
    return JSON.parse(str);
  }
  return '';
});

ipcMain.handle(QH_Events.SAVE_PAGE_INFO, (evidence, content) => {
  FileUtils.saveFile(content);
});

ipcMain.handle(QH_Events.COPY_PAGE_INFO, async (evidence, content) => {
  const str = await FileUtils.readFile();
  // 为了兼容后端mis的数据结构
  const json = [{ add_data: JSON.parse(str) }];
  clipboard.writeText(JSON.stringify(json));
});

ipcMain.handle(QH_Events.COPY_CONTENT, async (evidence, content) => {
  clipboard.writeText(content);
});